# coding: utf8

# 0. 置换变量
def exchange_variables():
	# No pythonic
	print ('No pythonic')
	a, b = 1, 2
	tmp = a
	a = b
	b = tmp
	print ('a=%s, b=%s' % (a, b))
	# is pythonic
	print ('is pythonic')
	a, b = 1, 2
	a, b = b, a
	print ('a=%s, b=%s' % (a, b))


# 1. 带索引的遍历集合
def ergodic_list():
	# No pythonic
	colors = ['red', 'green', 'blue', 'yellow']
	print ('No pythonic')
	for i in range(len(colors)):
		print (i, '--->', colors[i])
	# is pythonic
	print ('\npythonic')
	for i, color in enumerate(colors):
		print (i, '--->', color)


# 2.善用装饰器
def not_dec(str_, save={}):
	print save
	if str_ not in save:
		save[str_] = str_*2
		return str_*2
	else:
		return save[str_]

def decorator(func):
	save = {}
	def _in_dec(str_):
		print save
		if str_ not in save:
			save[str_] = func(str_)
		return save[str_]
	return _in_dec

@decorator
def dec(str_):
	return str_*2


def print_dec():
	print ('No pythonic')
	print not_dec('abc')
	print not_dec('abc')
	print ('\npythonic')
	print dec('abc')
	print dec('abc')


# 3.善用list
def good_list():
	print ('No pythonic')
	names = ['raymond', 'rachel', 'matthew', 'roger',
		'betty', 'melissa', 'judith', 'charlie']
	names.pop(0)
	names.insert(0, 'mark')
	print names
	
	print ('\npythonic')
	from collections import deque
	names = deque(['raymond', 'rachel', 'matthew', 'roger',
		'betty', 'melissa', 'judith', 'charlie'])
	names.popleft()
	names.appendleft('mark')
	print names


# 4.遍历字典的 key 和 value

def dict_():
	d = {'a': 1, 'b': 2}
	print('No pythonic')
	for k, v in d.items():
		print k, v
	print('\npythonic')
	for k, v in d.iteritems():
		print k, v


# 5.三目运行if/else

def if_else():
	print ('Not pythonic')
	gender = 'male'
	if gender == 'male':
		text = 'nan'
	else:
		text = 'nv'
	print text
	print ('\npythonic')
	text = 'nan' if gender=='male' else 'nv'
	print text

# 6.字符串格式化

def format_():
	print ('Not pythonic')
	print 'hello %s' % 'wd'
	print ('\npythonic')
	print 'hello {world}'.format(world='wd')


# 7.列表切片

def for_list_1():
	items = range(10)
	print ('Not pythonic')
	# 奇数
	odd_items = []
	for i in items:
		if i%2 !=0:
			odd_items.append(i)
	print odd_items
	# 拷贝
	copy_items = []
	for i in items:
		copy_items.append(i)
	print copy_items

def for_list_2():
	items = range(10, 21)
	print ('pythonic')
	# 奇数
	odd_items = items[1::2]
	print odd_items
	# 拷贝
	copy_items = items[:]
	print copy_items
	# 
	items.pop(0)
	print items
	print copy_items

# 8.善用生成器

def fab(max):
	n, a, b = 0, 0, 1
	while n < max:
		yield b
		a, b = b, a+b
		n += 1

# 9.获取字典元素

def get_dict_value():
	d = {'name': 'foo'}
	print ('Not pythonic')
	if d.has_key('name'):
		print d['name']
	else:
		print 'none'
	print ('pythonic')
	print d.get('name1', '=')

# 10.
def for_else():
	theflag = 11
	for i in xrange(10):
		if i == theflag:
			break
	else:
		print 2

# 11.字典推导式
def list_2_dict():
	L = xrange(4)
	D = {num:num*2 for num in L if num%2==0}
	print type(D)